﻿using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using Abp.Runtime.Session;
using OplugAbpProject.CMS.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OplugAbpProject.CMS
{
    public class CategoryAppService : AsyncCrudAppService<Category, CategoryDto, long, PagedResultRequestDto, CreateCategoryDto, UpdateCategoryDto>, ICategoryAppService
    {
        private readonly IObjectMapper _objectMapper;

        public CategoryAppService(IRepository<Category, long> repository, IObjectMapper objectMapper) : base(repository)
        {
            _objectMapper = objectMapper;
        }

        public async Task<List<CategoryTreeDto>> GetTreeListAsync(string layout)
        {
            var lists = await Repository.GetAllListAsync(o => o.Layout == layout && o.IsDeleted == false);
            List<CategoryTreeDto> result = GetTree(lists, 0);
            return result;
        }

        private List<CategoryTreeDto> GetTree(List<Category> items, long parentid)
        {
            List<CategoryTreeDto> result = new List<CategoryTreeDto>();
            var lists = items.Where(o => o.ParentId == parentid).ToList();
            foreach (var item in lists)
            {
                CategoryTreeDto dobj = _objectMapper.Map<CategoryTreeDto>(item);
                var childs = items.Where(o => o.ParentId == item.Id).ToList();
                if (childs.Count > 0)
                {
                    dobj.Childs = childs.Count;
                    dobj.children = GetTree(items, item.Id);
                }
                result.Add(dobj);
            }
            return result;
        }

        public async Task DeleteAsync(long[] ids)
        {
            await Repository.DeleteAsync(o => ids.Contains(o.Id));
        }
    }
}
